<script setup lang="ts">
import { ref, watch } from "vue";
import { message } from "@/utils/message";
import { FormInstance } from "element-plus";
import { addOrUpdatePoints } from "@/api/sysele";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  data: {
    type: Object,
    default: () => {
      return {};
    }
  },
  bmdata: {
    type: Object,
    default: () => {
      return [];
    }
  }
});

const ruleFormRef = ref<FormInstance>();

const formVisible = ref(false);
const formData = ref(props.data);
const selectedItems = ref([]);

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formData.value.manageid = JSON.stringify(selectedItems.value);
  await formEl.validate(valid => {
    if (valid) {
      addOrUpdatePoints(formData.value)
        .then(res => {
          if (res.success) {
            message("提交成功", { type: "success" });
            formVisible.value = false;
            resetForm(formEl);
            emit("add-up-search"); //用emit来进行事件通知传递
          } else {
            message("提交失败:" + res.errMsg, { type: "error" });
          }
        })
        .catch(error => {
          message("提交失败:" + JSON.stringify(error), { type: "error" });
        });
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const closeDialog = () => {
  formVisible.value = false;
  resetForm(ruleFormRef.value);
};

const emit = defineEmits(["update:visible", "add-up-search"]);
watch(
  () => formVisible.value,
  val => {
    emit("update:visible", val);
  }
);

watch(
  () => props.visible,
  val => {
    formVisible.value = val;
  }
);

watch(
  () => props.data,
  val => {
    formData.value = val;
  }
);

const rules = {
  type: [{ required: true, message: "请选择类型", trigger: "blur" }],
  quantity: [{ required: true, message: "请输入每次产生积分", trigger: "blur" }]
};
</script>

<template>
  <el-dialog
    v-model="formVisible"
    title="编辑积分配置"
    :width="680"
    draggable
    :before-close="closeDialog"
  >
    <!-- 表单内容 -->
    <el-form
      ref="ruleFormRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="发布类型" prop="type">
        <el-radio-group v-model="formData.type">
          <el-radio label="1">Banner</el-radio>
          <el-radio label="2">视频广告</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="排序" prop="quantity">
        <el-input
          v-model="formData.quantity"
          :style="{ width: '480px' }"
          placeholder="请输入每次产生积分"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        确定
      </el-button>
    </template>
  </el-dialog>
</template>
